/* eslint-disable array-callback-return */

import React from 'react';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, Button, Divider, Cascader } from 'antd';
import { connect } from 'dva';

const FormItem = Form.Item;
@connect(({ loading }) => ({
  loading: loading.models.supplier,
}))
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      listIndex: 0,
      addrList: [],
      isRequiredForm: [true],
      provCityAreaList: [],
    };
  }

  componentDidMount = () => {
    this.add();
    this.getAreaList(null, data => {
      data.map(item => {
        const temp = item;
        temp.label = item.areaName;
        temp.value = item.areaId;
        temp.isLeaf = false;
      });
      this.setState({ provCityAreaList: data });
    });
  };

  // 查询省市区
  getAreaList = (areaId, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'suppliermaintenance/queryNmAreaByParent',
      payload: { parentId: areaId },
      callback: res => {
        if (res.success && res.data.length) {
          callback(res.data);
        }
      },
    });
  };

  // 地区选择：省市区
  selectProvCityArea = (value, selectedOptions, id) => {
    const { form } = this.props;
    const getFields = `mailAreaName_${id}`;
    let mailArea = '';
    selectedOptions.map((item, index) => {
      mailArea += (index > 0 ? '/' : '') + item.areaName;
    });
    mailArea = mailArea.trim();
    form.setFieldsValue({ [getFields]: mailArea });
  };

  // 地区下拉数据
  loadAreaData = selectedOptions => {
    const { provCityAreaList } = this.state;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    const parentId = selectedOptions[selectedOptions.length - 1].areaId;
    targetOption.loading = true;
    const childrenData = [];
    this.getAreaList(parentId, data => {
      data.map(item => {
        const temp = item;
        temp.isLeaf = item.areaNature === 6;
        temp.label = item.areaName;
        temp.value = item.areaId;
        childrenData.push(item);
      });
    });
    // load options lazily
    setTimeout(() => {
      targetOption.loading = false;
      targetOption.children = childrenData;
      this.setState({
        provCityAreaList: [...provCityAreaList],
      });
    }, 1000);
  };

  // 新增数据
  add = () => {
    const { addrList, listIndex, isRequiredForm } = this.state;
    const newData = addrList.map(item => ({ ...item }));
    newData.push({
      id: `list_${listIndex}`,
      isRequired: true,
      contPerName: '联系人姓名',
      contPerPhone: '联系人电话',
      mailArea: '邮寄地址',
      mailAddr: '详细地址',
      remark: '备注',
    });
    this.state.listIndex += 1;
    const cRequiredForm = isRequiredForm;
    cRequiredForm.push(true);
    this.setState({ addrList: newData, isRequiredForm: cRequiredForm });
  };

  // 删除数据
  delList = id => {
    const { addrList } = this.state;
    const newData = addrList.filter(item => item.id !== id);
    this.setState({ addrList: newData });
  };

  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { addrList, provCityAreaList } = this.state;
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    return (
      <Form layout="vertical">
        {addrList.map((addrData, index) => (
          <div key={addrData.id}>
            {index ? <Divider /> : ''}
            <Row gutter={64}>
              <Col {...colProps}>
                <FormItem label={addrData.contPerName}>
                  {getFieldDecorator(`contPerName_${addrData.id}`, {
                    rules: [{ required: addrData.isRequired, message: '请输入' }],
                  })(<Input placeholder="请输入" maxLength="30" />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label={addrData.contPerPhone}>
                  {getFieldDecorator(`contPerPhone_${addrData.id}`, {
                    rules: [
                      {
                        required: addrData.isRequired,
                        message: '请正确输入手机号码或固话(最大限制12位)',
                        pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,12}$/,
                      },
                    ],
                  })(<Input placeholder="请输入" maxLength="12" />)}
                </FormItem>
              </Col>
              <Col {...colProps} style={{ display: 'none' }}>
                <FormItem>
                  {getFieldDecorator(`mailAreaName_${addrData.id}`, {
                    rules: [{ required: false, message: '请选择' }],
                  })(<Input />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label={addrData.mailArea}>
                  {getFieldDecorator(`mailArea_${addrData.id}`, {
                    rules: [{ required: addrData.isRequired, message: '请选择' }],
                  })(
                    <Cascader
                      placeholder="请选择"
                      options={provCityAreaList}
                      loadData={this.loadAreaData}
                      onChange={(value, selectedOptions) =>
                        this.selectProvCityArea(value, selectedOptions, addrData.id)
                      }
                      changeOnSelect
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col {...colProps}>
                <FormItem label={addrData.mailAddr}>
                  {getFieldDecorator(`mailAddr_${addrData.id}`, {
                    rules: [{ required: addrData.isRequired, message: '请输入' }],
                  })(<Input placeholder="请输入" maxLength="100" />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label={addrData.remark}>
                  {getFieldDecorator(`remark_${addrData.id}`, {
                    rules: [{ required: false, message: '请输入' }],
                  })(<Input placeholder="请输入" maxLength="200" />)}
                </FormItem>
              </Col>
              <Col {...colProps} />
              {index > 0 && (
                <Col
                  xl={{ span: 8 }}
                  lg={{ span: 8 }}
                  md={{ span: 8 }}
                  sm={24}
                  style={{ textAlign: 'center' }}
                >
                  <DeleteOutlined
                    className="dynamic-delete-button"
                    style={{ fontSize: '20px', lineHeight: '85px' }}
                    onClick={() => this.delList(addrData.id)} />
                </Col>
              )}
            </Row>
          </div>
        ))}
        <Button
          style={{ width: '100%', marginBottom: 8 }}
          type="dashed"
          icon={<PlusOutlined />}
          onClick={this.add}
        >
          新增邮寄地址
        </Button>
      </Form>
    );
  }
}
const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
